<template>
  <div class="login">
    <Row
      type="flex"
      justify="center"
      align="middle"
      @keydown.enter.native="submitForm"
      style="height:100%"
    >
      <Col class="layout">
        <div>
          <div>
            <Row class="header">
              <img src="../../assets/images/logo.jpg" width="220px">
              <div class="description">iview admin前后端分离开发</div>
            </Row>
          </div>
          <Row type="flex" justify="center" align="middle">
            <span style=" display: block;font-weight: bold;font-size: 16px;margin-bottom: 2vh;">忘记密码?</span>
            <Tabs v-model="formName">
              <TabPane label="手机号码找回" name="findByPhone" icon="md-phone-portrait">
                <Row>
                  <Form
                    ref="ruleForm"
                    :model="forgetForm"
                    :rules="ruleValidate"
                    class="form"
                    label-position="left"
                  >
                    <FormItem prop="phone">
                      <Input
                        v-model="forgetForm.phone"
                        size="large"
                        placeholder="请输入手机号码"
                        autocomplete="off"
                      />
                    </FormItem>
                    <FormItem prop="smsCode">
                      <Row type="flex">
                        <Input style="width: 68%" v-model="forgetForm.smsCode" placeholder="请输入短信验证码"></Input>
                        <Button style="margin-left: 10px;" :disabled="clickFlag" @click="sendSmsCode" size="large">{{text}}</Button>
                      </Row>
                    </FormItem>
                    <FormItem  prop="password">
                      <Input v-model="forgetForm.password" size="large" autocomplete="off" type="password" password placeholder="请输入密码"/>
                    </FormItem>
                    <FormItem  prop="confirmPassword">
                      <Input v-model="forgetForm.confirmPassword" ize="large" autocomplete="off"  type="password"  password placeholder="请再次输入密码"/>
                    </FormItem>
                  </Form>
                </Row>
              </TabPane>
              <TabPane label="邮箱找回" name="findByEmail" icon="md-mail">
                <Row>
                  <Form
                    ref="emailForm"
                    :model="forgetForm"
                    :rules="ruleValidate"
                    class="form"
                    label-position="left"
                  >
                    <FormItem prop="email">
                      <Input
                        v-model="forgetForm.email"
                        size="large"
                        placeholder="请输入邮箱地址"
                        autocomplete="off"
                      />
                    </FormItem>
                    <FormItem prop="emailCode">
                      <Row type="flex">
                        <Input style="width: 68%" v-model="forgetForm.emailCode" placeholder="请输入邮件验证码"></Input>
                        <Button style="margin-left: 10px;" :disabled="emailDisabled" @click="sendEmailCode" size="large">{{emailText}}</Button>
                      </Row>
                    </FormItem>
                    <FormItem  prop="password">
                      <Input v-model="forgetForm.password" ize="large" autocomplete="off"  type="password"  password placeholder="请输入密码"/>
                    </FormItem>
                    <FormItem  prop="confirmPassword">
                      <Input v-model="forgetForm.confirmPassword" ize="large" autocomplete="off"  type="password"  password placeholder="请再次输入密码"/>
                    </FormItem>
                  </Form>
                </Row>
              </TabPane>
            </Tabs>
            <Row type="flex" justify="center" style="width: 100%">
                <Button
                  class="login-btn"
                  type="primary"
                  style="width: 100%"
                  size="large"
                  long
                  @click="submitForm"
                  :loading="loading"
                  long>
                  重置密码
                </Button>
            </Row>
            <Row type="flex" justify="start" style="margin-top: 3vh;width: 100%">
              <router-link to="/login">
                <a class="forget-pass"><Icon type="md-arrow-back"/>返回</a>
              </router-link>
            </Row>
          </Row>
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import {checkUserExists,resetPasswd} from "@/api/user";
import {sendCode,sendEmailCode} from "@/api/login";

export default {
  data(){
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不得小于6位'));
      } else {
        callback();
      }
    };
    const validateConfirmPass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不得小于6位'));
      } else if(this.forgetForm.password!=value) {
        callback(new Error("两次输入的密码不一致"));
      }else{
        callback()
      }
    };
    const validatePhone = (rule, value, callback) => {
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error('手机号格式错误'));
      } else {
        checkUserExists(value).then(res=>{
          if(res.code===200){
            if(res.data){
              callback();
            }else{
              callback(new Error('手机号码不存在'));
            }
          }
        })
      }
    };
    const validateMail=(rule, value, callback)=>{
      let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (!reg.test(value)) {
          callback(new Error('邮箱格式不正确'));
        } else
          checkUserExists(value).then(res=>{
            if(res.code===200){
              if(res.data){
                callback();
              }else{
                callback(new Error('邮箱不存在'));
              }
            }
          })
    };
    return{
      loading: false,
      clickFlag:false,
      formName:'findByPhone',
      text:'获取验证码',
      emailText:'获取验证码',
      forgetForm: {
        confirmPassword:'',
        resetType:'phone',
      },
      count:60,
      emailDisabled:false,
      ruleValidate: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {validator:validatePhone,trigger: 'blur'}
        ],
        smsCode: [
          { required: true, message: '请输入短信验证码', trigger: 'blur' },
        ],
        emailCode: [
          { required: true, message: '请输入邮件验证码', trigger: 'blur' },
        ],
        email:[
          {required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {validator:validateMail}
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {validator:validatePass,trigger: 'blur'}
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {validator:validateConfirmPass,trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    submitForm () {
      if(this.formName=='findByPhone'){
        this.forgetForm.resetType='phone';
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
             console.log(valid)
             this.loading=true;
             resetPasswd(this.forgetForm).then(res=>{
                if(res.code===200){
                   this.$Message.success('重置成功.')
                   this.loading=false;
                   this.$router.push({path:'resetResult',query:{account:this.forgetForm.phone}})
                }else{
                  this.$Message.error(res.msg)
                  this.loading=false;
                  this.$refs.ruleForm.resetFields();
                }
             }).catch((error)=>{
               this.loading=false;
             })
          }
        })
      }else{
        this.forgetForm.resetType='email';
        this.$refs['emailForm'].validate((valid) => {
          if (valid) {
            console.log(valid)
            this.loading=true;
            resetPasswd(this.forgetForm).then(res=>{
              if(res.code===200){
                this.$Message.success('重置成功.')
                this.loading=false;
                this.$router.push({path:'resetResult',query:{account:this.forgetForm.email}})
              }else{
                this.$Message.error(res.msg)
                this.loading=false;
              }
            }).catch((error)=>{
              this.loading=false;
            })
          }
        })
      }
    },
    countDown(){
      let that = this;
      if (this.count == 0) {
        this.text='获取验证码';
        this.clickFlag=false;
        this.count=60
        return ;
      } else {
        this.text = this.count + " 秒后重试";
        this.count--;
        this.clickFlag=true;
      }
      setTimeout(function() {
        that.countDown();
      }, 1000);
    },
    countDownEmail(){
      let that = this;
      if (this.count == 0) {
        this.emailText='获取验证码';
        this.emailDisabled=false;
        this.count=60
        return ;
      } else {
        this.emailText = this.count + " 秒后重试";
        this.count--;
        this.emailDisabled=true;
      }
      setTimeout(function() {
        that.countDownEmail();
      }, 1000);
    },
    sendSmsCode(){
      this.$refs['ruleForm'].validateField('phone', (phoneError) => {
        if(!phoneError){
          sendCode(this.forgetForm.phone).then(res=>{
            if(res.code===200){
              this.$Message.success('发送成功.');
              this.countDown();
            }
          })
        }
      })
    },
    sendEmailCode(){
      this.$refs['emailForm'].validateField('email', (emailError) => {
        if(!emailError){
          sendEmailCode(this.forgetForm.email).then(res=>{
            if(res.code===200){
              this.$Message.success('邮件已发送，请注意查收邮件！');
              this.countDownEmail();
            }
          })
        }
      })
    }
  },
  mounted(){
  }
}
</script>


<style lang="less">
@import "./login.less";
.header {
  margin-top: 8vh;
  margin-bottom: 5vh;
  text-align: center;

  .description {
    font-size: 18px;
    color: rgba(0, 0, 0, 0.45);
    margin-top: 1vh;
  }
}
</style>
